<template>
  <div class="ribbon">
    <FloatCard v-show="isShowCard" @closeCard="clickCloce">
      <template slot="title">
        <span v-if="isEmail">电邮<b> (将本内容以PDF的形式分享至对方邮箱)</b></span>
        <span v-else>分享<b> (复制本内容的链接进行分享)</b></span>
      </template>
      <template slot="input">
        <el-input
          v-if="isEmail"
          class="input-with-select"
          v-model="to"
          placeholder="请输入对方邮箱"
        >
          <el-button slot="append" @click="affirmSend">确认</el-button>
        </el-input>
        <el-input
          v-else
          class="input-with-select"
          v-model="thisContentUrl"
          id="copyInput"
          readonly
        >
          <el-button slot="append" @click="clickCopy">复制</el-button>
        </el-input>
      </template>
    </FloatCard>
    <ul>
      <li @click="clickDy" :class="isShowCard && isEmail ? 'isActive' : ''">
        <svg-icon icon-class="dy_icon" />{{ detail.email }}
      </li>

      <li
        @click="clickfx"
        :class="isShowCard && isEmail == false ? 'isActive' : ''"
      >
        <svg-icon icon-class="fx_icon" />{{ detail.share }}
      </li>

      <!-- v-if="activeState" 判断是否有数据，如果还没有数据暂时不渲染 -->
      <!-- activeState.docFavoritesIsPraise等于1说明已经点赞，等于0没有点赞 -->
      <li
        v-if="activeState"
        @click="clickSc"
        :class="[
          activeState.docFavoritesIsPraise == 1 ? 'isActive' : '',
          isFavorites ? 'islight' : '',
        ]"
      >
        <svg-icon icon-class="sc_icon" />{{ activeState.docFavoritesNum }}
      </li>

      <!-- v-if="activeState" 判断是否有数据，如果还没有数据暂时不渲染 -->
      <!-- activeState.likeIsPraise等于1说明已经点赞，等于0没有点赞 -->
      <li
        v-if="activeState"
        @click="clickDz"
        :class="[
          activeState.likeIsPraise == 1 ? 'isActive' : '',
          isLike ? 'islight' : '',
        ]"
      >
        <svg-icon icon-class="dz_icon" />{{ activeState.likeNum }}
      </li>
    </ul>
    <div class="ribbon_btn">
      <!-- <el-button round @click="getProjectLink()">项目委托</el-button> -->
      <el-button round @click="getConsultLink()">我要咨询</el-button>
      <!-- pc -->
      <el-button
        type="primary"
        round
        class="ribbon_down"
        @click="clickDown"
        v-if="!['ios','android'].includes($isDevice)"
      >
        <span>下载文档</span>
        <span v-if="dwonCircle"><i class="el-icon-loading"></i></span>
      </el-button>
      <!-- ios 下载文档 -->
      <el-button
        type="primary"
        round
        class="ribbon_down"
        @click="clickDown('ios')"
        v-else
      >
        <span>下载文档</span>
      </el-button>

      <!-- <el-button
        type="primary"
        round
        class="ribbon_down"
        @click="clickDown('ios')"
      >
        <span>下载文档</span>
        <span v-if="dwonCircle"><i class="el-icon-loading"></i></span>
      </el-button> -->
    </div>
  </div>
</template>

<script>
import FloatCard from "./floatCard.vue";
import { getOrderListApi } from "@/BMViews/api/order.js";
import {
  getDocMailEmailApi,
  ifPurchaseMailApi,
  getOverallDownloadPdfApi,
} from "@/BMViews/api/doc/mail.js";
import { downloadfun } from "@/wss/utils/wss.js";
import {
  addDocTopShareApi,
  addDocTopEmailApi,
  addFavoritesApi,
  addLikeApi,
  removeLikeApi,
  removeFavoritesApi,
  addDocFavoritesApi,
} from "@/BMViews/api/doc/top.js";
export default {
  name: "Ribbon",
  components: { FloatCard },
  props: {
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    listActive: {
      type: [String, Number],
      default: "",
    },
    // 判断当前是否是推荐页面
    isFeat: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      goodsId: "", //文章的id
      status: "",
      type: "", //文章的类型
      goodsList: {}, //获取的文章列表

      to: "", //电邮发送链接
      activeDetail: {}, //当前这篇文章
      activeState: {}, //当前这篇文章的点赞收藏

      isShowCard: false, //是否显示电邮分享
      isEmail: true, //当前是否是电邮
      thisContentUrl: "", //当前内容的链接
      isEmailOrDown: false, // 是否点击的是true电邮还是false下载文档

      isFavorites: false, //是否收藏
      isLike: false, //是否点赞

      dwonCircle: false, // 下载显示的圈圈
    };
  },
  mounted() {
    this.activeDetail = this.detail;
    //获取文章的点赞收藏数量
    this.addDocFavorites();
    this.compUrl(); //计算当前的链接
    this.to = this.$store.state.user.email; //获取默认的邮箱地址

    //隐藏电邮和分享窗口 isShowCard
    this.$bus.$on("hiddenCard", (state) => {
      this.isShowCard = state;
    });
  },
  methods: {
    // 获取项目第一条链接
    getProjectLink(){
      let project = this.$router.options.routes.find(item=>{
        return item.path == "/Bm-project"
      })
      this.$router.push({path: project.children[0].path})
    },

    // 获取咨询第一条链接
    getConsultLink(){
      let consult = this.$router.options.routes.find(item=>{
        return item.path == "/Bm-Consult"
      })
      this.$router.push({path: consult.children[0].path})
    },

    //**************************电邮*********************** */
    //点击电邮
    async clickDy() {
      if (this.$store.getters.token) {
        //获取订单
        await this.ifPurchaseMail();
        //确认是否已经该买
        if (this.goodsList.ifPurchase) {
          //显示分享邮件
          this.isShowCard = true;
          this.isEmail = true;
        } else {
          // 判断当前是推荐页还是组件
          if (this.isFeat) {
            // console.log("推荐页面的支付显示");
            this.isEmailOrDown = true; // 是否点击的是true电邮还是false下载文档
            //通知推荐组件切换到支付页面
            this.$bus.$emit(
              "featHandlerShow",
              3,
              this.detail,
              this.goodsList,
              this.isEmailOrDown,
              this.isFeat
            );
          } else {
            // console.log("搜索页面的支付显示");
            this.isEmailOrDown = true; // 是否点击的是true电邮还是false下载文档
            //通知组件切换到支付页面
            this.$bus.$emit(
              "handlerShow",
              3,
              this.detail,
              this.goodsList,
              this.isEmailOrDown,
              this.isFeat
            );
          }
        }
      } else {
        this.$message({ type: "warning", message: "请登录！" });
        this.$router.push("/Bm-personalCenter/login");
      }
    },
    affirmSend() {
      if (this.$store.getters.token) {
        //发送电邮
        if (!this.to == "") {
          //发送电邮的接口
          this.getDocMailEmail();
        } else {
          this.$message("请填写邮箱地址");
        }
      }
    },
    //发送电邮接口
    async getDocMailEmail() {
      const { to } = this;

      let esType = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(esType == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let result = await getDocMailEmailApi({ to, esId, esType });
      if (result.code == 200) {
        this.$message({ message: "电邮发送成功！", type: "success" });
        //电邮数量+1
        this.addDocTopEmail();
        // 关闭电邮悬浮窗
        this.isShowCard = false;
      }
    },
    //电邮数量+1
    async addDocTopEmail() {
      let id = this.detail.id;
      let type = this.detail.esType || this.listActive;
      let result = await addDocTopEmailApi(id, type);
      if (result.code == 200) {
        //当前选中的文章电邮数+1
        this.handlerEmail();
      }
    },
    //**************************电邮*********************** end

    //**************************分享***********************
    //点击分享
    clickfx() {
      if (this.$store.getters.token) {
        this.isShowCard = true;
        this.isEmail = false;
        this.compUrl();
      } else {
        this.$message({ type: "warning", message: "请登录！" });
        this.$router.push("/Bm-personalCenter/login");
      }
    },
    //计算当前的链接
    compUrl() {
      let ly = this.$route.fullPath;
      this.thisContentUrl =
        "http://www.wensanshi.com" +
        ly.split("?")[0] +
        "?id=" +
        this.detail.id +
        "&esType=" +
        (this.detail.esType || this.listActive);
    },
    //电邮分享点击关闭按钮
    clickCloce() {
      this.isShowCard = false;
    },
    //点击复制
    async clickCopy() {
      let copyVal = document.getElementById("copyInput");
      // console.log(copyVal);
      copyVal.select();
      document.execCommand("Copy");
      this.$message({
        message: "复制成功",
        type: "success",
      });
      let id = this.detail.id;
      let type = this.detail.esType || this.listActive;
      //分享点击数接口
      let result = await addDocTopShareApi(id, type);
      if (result.code == 200) {
        //当前选中的文章分享数+1
        this.handlerShare();
      }
    },
    //**************************分享***********************end

    //**************************点击下载***********************
    //点击下载文档按钮
    async clickDown(isIos) {
      if (this.$store.getters.token) {
        //获取订单的列表
        await this.ifPurchaseMail();

        //查询订单接口：判断如果在订单里面并且已经支付状态是成功的可以直接下载
        if (this.goodsList.ifPurchase) {
          // 在订单里面并且已经支付状态是成功的可以直接下载
          if (isIos == "ios") {
            this.$message({ type: "success", message: "正在下载，请稍等！" });
            this.getOverallDownloadPdfIos();
          } else {
            this.$message({ type: "success", message: "正在下载，请稍等！" });
            this.getOverallDownloadPdf(); //下载的接口
          }
        } else {
          // 判断当前是推荐页还是组件
          if (this.isFeat) {
            // console.log("推荐页面的支付显示");
            this.isEmailOrDown = false; // 是否点击的是true电邮还是false下载文档
            //通知推荐组件切换到支付页面
            this.$bus.$emit(
              "featHandlerShow",
              3,
              this.detail,
              this.goodsList,
              this.isEmailOrDown
            );
          } else {
            // console.log("搜索页面的支付显示");
            this.isEmailOrDown = false; // 是否点击的是true电邮还是false下载文档
            //通知组件切换到支付页面
            this.$bus.$emit(
              "handlerShow",
              3,
              this.detail,
              this.goodsList,
              this.isEmailOrDown
            );
          }
        }
      } else {
        this.$message({ type: "warning", message: "请登录！" });
        this.$router.push("/Bm-personalCenter/login");
      }
    },
    // 下载文档的接口（）ios）
    async getOverallDownloadPdfIos() {
      const { to } = this;

      let type = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(type == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let result = await getOverallDownloadPdfApi({ esId, type });
      if (result.code == 200) {
        // 下载文件***************
        let url = result.msg;
        // let fileName = url.substring(url.lastIndexOf("/") + 1); //获取文件名称
        let a = document.createElement("a");
        a.style.display = "none";
        document.body.appendChild(a);
        a.href = url;
        a.click();
        // 下载文件***************end

        //显示推荐页面
        // this.$bus.$emit('featHandlerShow', 1)
      }

      // let a = document.createElement("a");
      // a.style.display = "none";
      // document.body.appendChild(a);
      // a.href =
      //   "http://jadinec-test.oss-accelerate.aliyuncs.com/excelFile/a5f23e130d5e4dd7adda942c45207927.pdf";
      // a.click();
    },
    //查询订单列表（对比是否当前文章已支付）
    async ifPurchaseMail() {
      let type = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(type == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let title = this.detail.title || this.detail.name;
      let result = await ifPurchaseMailApi({ esId, type });
      if (result.code == 200) {
        this.goodsList = result;
      }
    },

    // 下载文档的接口
    async getOverallDownloadPdf() {
      this.dwonCircle = true; //显示加载圈圈
      const { to } = this;
      let type = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(type == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let result = await getOverallDownloadPdfApi({ esId, type });
      if (result.code == 200) {
        // 下载文件***************
        let url = result.msg;
        let fileName = url.substring(url.lastIndexOf("/") + 1); //获取文件名称
        downloadfun(fileName, url); // 下载文件需要引入
        // 下载文件***************end

        this.dwonCircle = false; //隐藏加载圈圈
        //显示推荐页面
        // this.$bus.$emit('featHandlerShow', 1)
      }
    },
    //**************************点击下载***********************end

    // 获取当前文章的点赞收藏
    async addDocFavorites() {
      let result = await addDocFavoritesApi(this.detail.id);
      if (result.code == 200) {
        this.activeState = result.data;
      }
    },
    // **************************收藏**************************
    //点击收藏按钮
    clickSc() {
      if (this.$store.getters.token) {
        if (
          this.isFavorites == true ||
          this.activeState.docFavoritesIsPraise > 0
        ) {
          //收藏的取消接口
          this.removeFavorites();
          this.handlerFavorites(-1);
          this.isFavorites = false;
        } else {
          //收藏的添加接口
          this.addFavorites();
          this.handlerFavorites(1);
          this.isFavorites = true;
        }
      } else {
        this.$message({ type: "warning", message: "请登录！" });
        this.$router.push("/Bm-personalCenter/login");
      }
    },
    //收藏的添加接口
    async addFavorites() {
      console.log(this.detail, "温柔温柔温柔温柔温柔温柔");
      let esType = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(esType == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let esName = this.detail.title || this.detail.name;
      let esFrom = this.detail.from;
      let publishTime = this.detail.createTime;
      // 内容摘要
      let content = ''
      if(esType == '1'){
        // 法条
        if(!this.detail.history) return //没有的话就返回
        content = this.detail.history
      }else if(esType == '2'){
        // 解答
        if(!this.detail.answerStr) return //没有的话就返回
        content = this.detail.answerStr
      }else if(esType == '3'){
        // 政策
        if(!this.detail.infoStr) return //没有的话就返回
        content = this.detail.infoStr
      }else if(esType == '4'){
        // 合同
        if(!this.detail.infoStr) return //没有的话就返回
        content = this.detail.infoStr
      }
      // 内容摘要 end
      let result = await addFavoritesApi({
        esType,
        esId,
        esName,
        esFrom,
        publishTime,
        content: content.substring(0,290)
      });
      if (result.code == 200) {
        this.$message({
          message: "收藏成功",
          type: "success",
        });
      }
    },
    //取消收藏的接口
    async removeFavorites() {
      let esType = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(esType == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let result = await removeFavoritesApi({ esId });
      if (result.code == 200) {
        this.$message({
          message: "取消收藏成功",
          type: "success",
        });
      }
    },

    // **************************收藏**************************end

    // **************************点赞**************************
    //点击点赞按钮
    clickDz() {
      if (this.$store.getters.token) {
        if (this.isLike == true || this.activeState.likeIsPraise > 0) {
          //点赞的取消接口
          this.removeLike();
          this.handlerLike(-1);
          this.isLike = false;
        } else {
          //点赞的添加接口
          this.addLike();
          this.handlerLike(1);
          this.isLike = true;
        }
      } else {
        this.$message({ type: "warning", message: "请登录！" });
        this.$router.push("/Bm-personalCenter/login");
      }
    },
    //点赞的添加接口
    async addLike() {
      let type = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(type == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let userId = this.$store.state.user.userId;
      let userName = this.$store.state.user.name;
      let avatar = this.$store.state.user.avatar;
      let result = await addLikeApi({ type, esId, userId, userName, avatar });
      if (result.code == 200) {
        this.$message({
          message: "点赞成功",
          type: "success",
        });
      }
    },
    //取消点赞接口
    async removeLike() {
      let esType = this.detail.esType || this.listActive;//类型
      let esId = "";
      // 解答和政策要截取
      if(esType == '1'){
        // 判断id超过20位截取一半
        let arr = this.detail.id.split("");
        if (arr.length > 20) {
          esId = this.detail.id.slice(0, 16);
        } else {
          esId = this.detail.id;
        }
      }else{
        esId = this.detail.id
      }

      let result = await removeLikeApi({ esId });
      if (result.code == 200) {
        this.$message({
          message: "取消点赞成功",
          type: "success",
        });
      }
    },
    // **************************点赞**************************end

    //修改当前选中文章的分享数+1
    handlerShare() {
      this.activeDetail.share = this.activeDetail.share + 1;
    },
    //修改当前选中文章的电邮数+1
    handlerEmail() {
      this.activeDetail.email = this.activeDetail.email + 1;
    },
    //点击收藏添加类名,并且数量+1
    handlerFavorites(num) {
      if (num > 0) {
        // 大于0加一
        this.activeState.docFavoritesNum =
          parseInt(this.activeState.docFavoritesNum) + 1;
      } else {
        //小于0减一
        this.activeState.docFavoritesNum =
          parseInt(this.activeState.docFavoritesNum) - 1;
        //当前的是否收藏-1，主要是视图更新-1
        this.activeState.docFavoritesIsPraise =
          this.activeState.docFavoritesIsPraise - 1;
        this.isFavorites = false;
      }
    },
    //点击点赞添加类名,并且数量+1
    handlerLike(num) {
      if (num > 0) {
        // 大于0加一
        this.activeState.likeNum = parseInt(this.activeState.likeNum) + 1;
      } else {
        //小于0减一
        this.activeState.likeNum = parseInt(this.activeState.likeNum) - 1;
        //当前的是否点赞-1，主要是视图更新-1
        this.activeState.likeIsPraise = this.activeState.likeIsPraise - 1;
        this.isLike = false;
      }
    },
  },
  watch: {
    //监听切换文章的时候，把这两个改回默认值，避免上一次的点赞收藏的影响
    "detail.id"(oldValue, newValue) {
      this.isFavorites = false; //是否收藏
      this.isLike = false; //是否点赞
      this.activeDetail = this.detail;
      //获取文章的点赞收藏数量
      this.addDocFavorites();

      // 隐藏电邮和分享的弹框
      this.isShowCard = false;
    },
  },
};
</script>

<style scoped>
.ribbon {
  width: 100%;
  display: flex;
  padding: 10px 30px;
  justify-content: space-between;
  align-items: center;
  height: 54px;
  position: relative;
}
.ribbon > ul {
  display: flex;
  padding: 0;
}
.ribbon > ul li {
  display: flex;
  align-items: center;
  cursor: pointer;
  list-style: none;
  color: #999;
  margin-right: 30px;
  font-size: 12px;
}
.ribbon > ul li > svg {
  display: block;
  width: 14px;
  height: 14px;
  margin-right: 8px;
  font-size: 14px;
  color: #b7b7b7;
}
.ribbon > ul li.isActive,
.ribbon > ul li.islight,
.ribbon > ul li.isActive svg,
.ribbon > ul li.islight svg {
  color: #f87a23;
}
.ribbon .ribbon_btn {
  margin-top: 0px;
}
.ribbon .ribbon_btn .el-button {
  color: #f87a23;
  border-color: #f87a23;
  font-size: 12px;
}
.ribbon .ribbon_btn .ribbon_down {
  color: #fff;
  background-color: #f87a23;
  margin-left: 10px;
}
.ribbon .ribbon_btn .el-button:hover {
  background-color: #f89723;
  color: #fff;
}

::v-deep .input-with-select.el-input.is-disabled .el-input__inner {
  color: #333;
  cursor: text;
}

@media (max-width: 1180px) {
  .ribbon > ul {
    width: 42%;
  }
  .ribbon > ul li {
    margin-right: 20px;
  }
  .ribbon > ul li > svg {
    margin-right: 4px;
  }
  .ribbon .ribbon_btn .el-button {
    padding: 8px 14px;
  }
  .ribbon .ribbon_btn > a:nth-child(2) {
    margin-left: 5px !important;
  }
  .ribbon .ribbon_btn .ribbon_down {
    margin-left: 5px;
  }
}

@media (max-width: 1120px) {
  .ribbon > ul {
    width: 42%;
  }
  .ribbon > ul li {
    margin-right: 15px;
  }
  .ribbon > ul li > svg {
    margin-right: 4px;
  }
  .ribbon .ribbon_btn .el-button {
    padding: 6px 10px;
  }
  .ribbon .ribbon_btn > a:nth-child(2) {
    margin-left: 5px !important;
  }
  .ribbon .ribbon_btn .ribbon_down {
    margin-left: 5px;
  }
}
</style>
